package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 杨林
 * @create 2022-11-06 22:50 星期日
 * description:
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> paramMap) {

        //json转对象
        String jsonString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);

        //判断是否为空
        if (department == null){
            throw new YyghException(20001,"数据异常");
        }

        //判断科室是否存在
        String hoscode = department.getHoscode();
        String depcode = department.getDepcode();
        Department existDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);

        //判断是否为空，如果为空则添加  如果不为空，则修改
        if (existDepartment == null){
            //添加
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
        }else{
            //修改
            department.setId(existDepartment.getId());
            department.setUpdateTime(new Date());
            department.setCreateTime(existDepartment.getCreateTime());
        }

        departmentRepository.save(department);
    }

    /**
     * 分页查询科室
     *
     */
    @Override
    public Page<Department> selectPage(Integer pageNum, Integer limit, DepartmentQueryVo departmentQueryVo) {

        //1.排序  按照创建时间降序排列
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        //分页  （页码从0开始）
        Pageable pageable = PageRequest.of(pageNum - 1, limit, sort);

        //查询条件  将departmentQueryVo转换成department
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);

        //mo模糊查询匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //模糊查询
                .withIgnoreCase(); //忽略大小写

        //example对象
        Example<Department> example = Example.of(department, matcher);

        //调用findAll()方法
        Page<Department> page = departmentRepository.findAll(example, pageable);
        return page;
    }

    /**
     * 删除科室
     */
    @Override
    public void remove(String hoscode, String depcode) {

        //查询科室是否存在
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);

        //根据id删除
        if (department != null){
            departmentRepository.deleteById(department.getId());
        }

    }

    /**
     * 根据医院编号 查询所有的小科室列表
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //DepartmentVo中包含科室编号 科室名称 下级节点

        //用于封装查询到的医院下所有的科室列表
        List<DepartmentVo> result = new ArrayList<>();

        //1.根据hosCode查询所有科室
        Department department = new Department();
        department.setHoscode(hoscode);
        //用于模糊匹配的数据
        Example example = Example.of(department);
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据bigcode进行分组(Map(大科室编号，大科室编号下对应的全局数据))
        Map<String,List<Department>> departmentMap = departmentList.stream().collect( //size = 12 共有12个大科室
                Collectors.groupingBy(Department::getBigcode)
        );

        //遍历departmentMap
        Set<Map.Entry<String, List<Department>>> entrySet = departmentMap.entrySet();
        for (Map.Entry<String, List<Department>> entry : entrySet) {
            //获取大科室编号
            String bigcode = entry.getKey();
            //获取大科室编号下对应的全局数据
            List<Department> department1List = entry.getValue();

            //封装大科室数据 （每遍历一次，创建一个大科室对象）
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bigcode);
            departmentVo1.setDepname(department1List.get(0).getBigname());

            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department1 : department1List) {
                DepartmentVo departmentVo2 = new DepartmentVo();
                departmentVo2.setDepcode(department1.getDepcode());
                departmentVo2.setDepname(department1.getDepname());
                //将数据封装到children集合中
                children.add(departmentVo2);
            }

            //把小科室集合封装到对应的大科室中
            departmentVo1.setChildren(children);

            //将封装好的大科室数据放在result中
            result.add(departmentVo1);
        }
        //返回result
        return result;
    }

    //根据hoscode 和 depcode查询depName
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        return department.getDepname();
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
